import  Vue  from "vue"
import Vuex from 'vuex'

const socket=new Vuex.Store({
	state:{
		socketTask:null
	},
	mutations:{
		websoketInit(state,url){
			state.socketTask=uni.connectSocket({
				url,
					success(){
						console.log("socket连接成功")
					}
			})
			state.socketTask.onOpen((res)=>{
				console.log("socket已打开")
				state.socketTask.onMessage(function(res){
					console.log("收到服务器信息",res.data)
				})
			})
		},
		websoketSend(state,data){
			let dt=JSON.stringify(data)
			console.log("socket_data",dt)
			state.socketTask.send({
				data:dt,
				success() {
					console.log("消息发送成功")
				}
			})
		},
		close_socket(state){
			if(!state.socketTask)
				return;
			state.socketTask.close({
				success(){
					console.log("关闭成功")
				},
				fail(err){
					console.log("关闭失败",err)
				}
			})
		}
	},
	actions:{
		websoketInit({
			commit
		},url){
			commit('websoketInit',url)
		},
		websoketSend({
			commit
		},data){
			commit('websoketSend',data)
		},
		close_socket({
			commit
		}){
			commit('close_socket')
		},
	}
})

export default socket